<template>
  <div>
    <div class="header">
      <el-button v-if="previewVisible" type="primary" @click="print" class="print">打印</el-button>
      <!-- 关闭预览按钮固定在右上角 -->
      <el-button v-if="previewVisible" type="danger" @click="closePreview" class="close-preview-btn">
        关闭预览
      </el-button>
    </div>

    <!-- docx、xlsx 和 pdf 文件预览 -->
    <div class="container" ref="container" v-show="previewVisible">
      <!-- 预览内容渲染在这里 -->
      <div ref="previewContent" class="preview-content"></div>
    </div>
  </div>
</template>

<script>
import { renderAsync } from "docx-preview";
import jsPreviewExcel from "@js-preview/excel";
import "@js-preview/excel/lib/index.css";
import axios from "axios";
import { EventBus } from '../utils/EventBus'


export default {
  data() {
    return {
      previewVisible: false,
      previewContent: null,  // 统一的预览容器

    };
  },
  created() {
    EventBus.$on('revFileName', this.fetchFileForPreview)
  },
  mounted() {

    this.previewContent = this.$refs.previewContent; // 初始化 previewContent 引用
  },
  beforeDestroy() {
    EventBus.$off('revFileName', this.fetchFileForPreview)
  },
  methods: {
    print() {
      window.print();
    },

    async fetchFileForPreview(filename) {
      try {
        const response = await axios.get(`/download/${filename}`, { responseType: 'arraybuffer' });
        const file = new Blob([response.data]);
        const fileExtension = filename.split('.').pop().toLowerCase();

        this.previewVisible = true;

        if (fileExtension === 'docx') {
          this.previewDocx(file);
        } else if (fileExtension === 'xlsx' || fileExtension === 'xls') {
          this.previewXlsx(file);
        } else {
          alert('Unsupported file type');
        }
      } catch (error) {
        console.error('Error fetching file:', error);
        alert("获取文件时出错，请稍后重试。");
      }
    },

    // 预览 docx 文件
    async previewDocx(blob) {
      // 检查文件是否为空
      if (blob.size === 0) {
        alert('文件为空，无法预览');
        return;
      }
      const fileReader = new FileReader();
      // 将 blob 读取为 ArrayBuffer
      fileReader.readAsArrayBuffer(blob);
      fileReader.onload = async () => {
        // 清空之前的内容
        this.previewContent.innerHTML = '';

        try {
          // 确保读取的结果不为空
          if (!fileReader.result) {
            throw new Error('文件内容为空');
          }

          // 使用 docx-preview 渲染 docx 文件
          await renderAsync(
            fileReader.result,
            this.previewContent,
            this.previewContent,
            {
              className: "docx",
              inWrapper: true,
              ignoreWidth: false,
              ignoreHeight: false,
              ignoreFonts: false,
              breakPages: true,
              renderHeaders: true,
              renderFooters: true,
              renderFootnotes: true,
              renderEndnotes: true,
              debug: false,
            }
          );
        } catch (error) {
          console.error("Error rendering docx:", error);
          this.previewVisible = false;
          alert("这个文件可能已经损坏，请下载查看");
        }
      };



    },

    // 处理 xlsx 文件的预览
    previewXlsx(file) {
      // 清空之前的内容
      this.previewContent.innerHTML = '';
      // 禁止背景页面滚动
      document.body.style.overflow = 'hidden';
      const url = URL.createObjectURL(file);

      // 使用 Vue 的 nextTick 确保容器渲染完成后再初始化预览
      this.$nextTick(() => {
        const excelPreviewer = jsPreviewExcel.init(this.previewContent);
        excelPreviewer.preview(url); // 使用 js-preview/excel 进行预览
      });
    },


    // 关闭预览
    closePreview() {
      this.previewVisible = false;
      this.previewContent.innerHTML = ''; // 清空预览容器内容
      // 恢复背景页面滚动
      document.body.style.overflow = '';
    },
  },
};
</script>

<style scoped lang="scss">
.header {
  position: fixed;
  left: 20px;
  top: 20px;
}

.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-content {
  position: fixed;
  top: 100px;
  left: 140px;
  width: 80%;
  height: 90vh;
  /* 调整为需要的大小 */
  overflow: auto;
  border: 1px solid #ccc;
  padding: 10px;
  margin-left: 120px;

  iframe {
    border: none;
  }
}

.close-preview-btn {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 10;
}

.print {
  position: fixed;
  top: 20px;
  right: 150px;
  z-index: 10;
}

@media print {
  .header {
    display: none;
  }
}
</style>
